package com.itmuch.box.controller.front.member;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.itmuch.box.core.base.BaseController;
import com.itmuch.box.core.security.SubjectUtil;
import com.itmuch.box.domain.category.entity.Category;
import com.itmuch.box.domain.content.entity.Content;
import com.itmuch.box.domain.content.entity.ContentArticle;
import com.itmuch.box.domain.content.vo.ArticleAddVo;
import com.itmuch.box.domain.content.vo.ArticleEditVo;
import com.itmuch.box.domain.sort.entity.Sort;
import com.itmuch.box.domain.tag.entity.Tag;
import com.itmuch.box.service.category.CategoryService;
import com.itmuch.box.service.content.ContentArticleService;
import com.itmuch.box.service.content.ContentService;
import com.itmuch.box.service.sort.SortService;
import com.itmuch.box.service.tag.TagService;
import com.itmuch.box.util.DozerUtil;
import com.itmuch.box.util.UrlUtil;

@Controller
@RequestMapping("/member/article")
public class MemberCenterArticleController extends BaseController {
    @Resource
    private ContentService contentService;
    @Resource
    private ContentArticleService contentArticleService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private SortService sortService;
    @Resource
    private TagService tagService;

    /**
     * 添加稿件
     * @return 页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView add() {
        Set<Category> categories = this.categoryService.findByModelId(1);

        // 默认标签
        Set<Tag> defaultTags = this.tagService.findDefault();
        return new ModelAndView("front/member/center/article/add").addObject("categories", categories).addObject("defaultTags", defaultTags);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@Valid @ModelAttribute("articleVo") ArticleAddVo vo, BindingResult result, HttpServletRequest req, RedirectAttributes ra) {
        if (!result.hasErrors()) {
            this.contentArticleService.insertArticle(vo);

            return UrlUtil.success(ra, "添加文章成功", req.getContextPath() + "/member/article/1");
        }
        // JSR校验不通过
        return "front/member/center/article/add";
    }

    /**
     * 列表文章
     * @param pageNo 页码
     * @param req 请求
     * @return 列表页面
     */
    @RequestMapping("/{pageNo}")
    public ModelAndView listArticles(@PathVariable Integer pageNo, HttpServletRequest req) {
        Integer memberId = SubjectUtil.getSubjectId();

        Page<Content> pageInfo = this.contentService.findByMemberIdAndModelId(memberId, 1, new PageRequest(pageNo - 1, 10));
        String url = req.getContextPath() + "/member/article";
        return new ModelAndView("front/member/center/article/list").addObject("list", pageInfo).addObject("url", url);
    }

    @RequestMapping("/del/{id}")
    public String deleteById(@PathVariable Integer id, HttpServletRequest req, RedirectAttributes ra) {
        this.contentArticleService.deleteArticleById(id);
        String url = req.getContextPath() + "/member/article/1";
        return UrlUtil.success(ra, "文章删除成功", url);
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String updateById(@PathVariable Integer id, HttpServletRequest req, RedirectAttributes ra) {
        Integer memberId = SubjectUtil.getSubjectId();

        Content content = this.contentService.findOne(id);
        if (content != null) {
            ArticleEditVo articleEditVo = DozerUtil.map(content, ArticleEditVo.class);
            if (memberId.equals(content.getMemberId())) {
                ContentArticle contentArticle = this.contentArticleService.findOne(id);
                if (contentArticle != null) {
                    DozerUtil.map(contentArticle, articleEditVo);
                }
                Set<Tag> tags = this.tagService.findByContentId(id);
                if (CollectionUtils.isNotEmpty(tags)) {
                    StringBuffer tagStringBuff = new StringBuffer();
                    String tagStr = "";
                    if ((tags != null) && !tags.isEmpty()) {
                        for (Tag tag : tags) {
                            tagStringBuff.append(tag.getName()).append(",");
                        }
                        if (tagStringBuff.length() > 1) {
                            tagStr = tagStringBuff.substring(0, tagStringBuff.length() - 1);
                        }
                    }
                    articleEditVo.setTagsString(tagStr);
                }

                Set<Category> categories = this.categoryService.findByModelId(1);
                Set<Tag> defaultTags = this.tagService.findDefault();

                List<Sort> sorts = this.sortService.findByCategoryIdRecursion(content.getCategoryId());

                req.setAttribute("editVo", articleEditVo);
                req.setAttribute("categories", categories);
                req.setAttribute("defaultTags", defaultTags);
                req.setAttribute("sorts", sorts);

                return "front/member/center/article/edit";
            }
            //  // 不是用户自己的
            else {
                return UrlUtil.error(ra, "请勿修改他人内容", req.getContextPath() + "/member/article/1");
            }

        }
        // 不是用户自己的
        else {
            return UrlUtil.error(ra, "该内容不存在", req.getContextPath() + "/member/article/1");
        }

    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
    public String updateById(@PathVariable Integer id, @ModelAttribute("editVo") @Valid ArticleEditVo editVo, BindingResult result,
            HttpServletRequest req, RedirectAttributes ra) {
        if (!result.hasErrors()) {
            this.contentArticleService.updateArticle(editVo);
            // 成功
            return UrlUtil.success(ra, "修改成功", req.getContextPath() + "/member/article/1");
        }
        // JSR校验失败
        else {
            ArticleEditVo articleEditVo = this.contentArticleService.findArticleById(id);

            Integer categoryId = articleEditVo.getCategoryId();
            Category category = this.categoryService.findOne(categoryId);
            List<Sort> sorts = this.sortService.findByCategoryId(categoryId);

            // 所有的推荐方式
            req.setAttribute("category", category);
            req.setAttribute("sorts", sorts);
            return "back/content/article/edit";
        }

        /*if (!result.hasErrors()) {
            Content content = this.contentService.selectById(id);
            if (content != null) {
                Integer memberId = SubjectUtil.getSubjectId();
                if (memberId.equals(content.getMemberId())) {
                    this.contentArticleService.updateArticleVo(editVo);
                    return UrlUtil.success(ra, this.frontPath, "修改文章成功", this.frontPath + "/member/article/1");
                }
                // 用户修改的不是自己的内容
                else {
                    return UrlUtil.error(ra, this.frontPath, "请勿修改他人内容", req.getContextPath() + this.frontPath + "/member/article/1");
                }
            }
            // 文章不存在
            else {
                return UrlUtil.error(ra, this.frontPath, "该内容不存在", req.getContextPath() + this.frontPath + "/member/article/1");
            }
        }
        // 没有通过校验
        List<Category> categories = this.categoryService.selectByModelId(1);
        // 默认标签
        List<Tag> defaultTags = this.tagService.selectDefault();
        req.setAttribute("categories", categories);
        req.setAttribute("defaultTags", defaultTags);
        return "front/member/center/article/edit";*/
    }
}
